package cn.szzsi.common.file;

import cn.szzsi.core.CoreConfig;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/* * 文件上传工具
 * Created by zhengy on 2017/3/24.
 */
public class QiniuUtil  {
    public static cn.szzsi.core.file.QiniuUtil qu=new cn.szzsi.core.file.QiniuUtil();

    //设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = CoreConfig.p.get("ACCESS_KEY");
    String SECRET_KEY = CoreConfig.p.get("SECRET_KEY");
    //填写新建的那个存储空间对象的名称
    String bucketname = CoreConfig.p.get("bucketname");
    //密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    //创建上传对象
    Configuration configuration = new Configuration(Zone.zone0());
    private  UploadManager uploadManager = new UploadManager(configuration);

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken(){
        return auth.uploadToken(bucketname);
    }
    //普通上传

    /**
     *
     * @param filePath //本地要上传文件路径
     * @param fileName //上传到七牛后保存的文件名
     */
    public boolean upload(String filePath,String fileName) {
        DefaultPutRet putRet=null;
        Response res=null;
        try {
            //调用put方法上传
            res = uploadManager.put(filePath, fileName, getUpToken());
            putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
        } catch (QiniuException e) {
            Response r = e.response;
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
        return res.isOK();
    }

}



